package aygx.automatic.condition;

import aygx.automatic.annotation.ConditionOnClass;
import org.springframework.context.annotation.Condition;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;

import java.util.Map;

/**
 * @author 暗影孤星
 * @date 2020/10/27 22:50
 * @explanation
 */
public class ClassCondition implements Condition {
    /**
     * @param conditionContext      上下文对象。用于获取环境，IOC容器，ClassLoader对象
     * @param annotatedTypeMetadata 注解元对象。 可以用于获取注解定义的属性值
     * @return
     */
    @Override
    public boolean matches(ConditionContext conditionContext, AnnotatedTypeMetadata annotatedTypeMetadata) {
        boolean flag = false;
        // 获取注解属性
        Map<String, Object> multiValueMap = annotatedTypeMetadata.getAnnotationAttributes(ConditionOnClass.class.getName());
        if (multiValueMap != null) {
            String[] classNames = (String[]) multiValueMap.get("value");
            for (String className : classNames) {
                try {
                    Class.forName(className);
                    flag = true;
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }

        return flag;
    }
}
